# switch_network.py
import sys
import json
import subprocess
from utils.admin_util import is_admin, run_as_admin
from utils.config_manager import NetworkConfigManager


def switch_network(network_type):
    """执行实际的网络切换操作（需要管理员权限）"""
    config_manager = NetworkConfigManager()
    config = config_manager.get_network_config(network_type)

    adapter_name = "以太网"  # 或从配置文件获取

    if config.get("dhcp", False):
        # 设置DHCP
        subprocess.run(
            f'netsh interface ip set address name="{adapter_name}" source=dhcp',
            shell=True,
            check=True,
        )
        subprocess.run(
            f'netsh interface ip set dnsservers name="{adapter_name}" source=dhcp',
            shell=True,
            check=True,
        )
    else:
        # 设置静态IP
        ip = config["ip"]
        mask = config["mask"]
        gateway = config.get("gateway", "")
        dns1 = config.get("dns1", "")
        dns2 = config.get("dns2", "")

        cmd = f'netsh interface ip set address name="{adapter_name}" static {ip} {mask} {gateway} 1'
        subprocess.run(cmd, shell=True, check=True)

        if dns1:
            subprocess.run(
                f'netsh interface ip set dnsservers name="{adapter_name}" static {dns1} primary',
                shell=True,
                check=True,
            )
        if dns2:
            subprocess.run(
                f'netsh interface ip add dnsservers name="{adapter_name}" {dns2} index=2',
                shell=True,
                check=True,
            )


if __name__ == "__main__":
    if len(sys.argv) > 1:
        if not is_admin():
            run_as_admin()
        switch_network(sys.argv[1])
